package com.ysx.server.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ysx.server.mapper.CommentMapper;
import com.ysx.server.mapper.GoodsMapper;
import com.ysx.server.mapper.UserMapper;
import com.ysx.server.pojo.dto.CommentAddDTO;
import com.ysx.server.pojo.dto.CommentPageQueryDTO;
import com.ysx.server.pojo.entity.Comment;
import com.ysx.server.pojo.entity.Goods;
import com.ysx.server.pojo.entity.User;
import com.ysx.server.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 评论分页查询
     *
     * @param commentPageQueryDTO
     * @return
     */
    @Override
    public Page<Comment> page(CommentPageQueryDTO commentPageQueryDTO) {
        PageHelper.startPage(commentPageQueryDTO.getCurrent(),commentPageQueryDTO.getPageSize());
        return commentMapper.page(commentPageQueryDTO);
    }

    /**
     * 修改评论信息
     *
     * @param comment
     * @return
     */
    @Override
    public boolean update(Comment comment) {
        if(comment==null){
            return false;
        }
        return commentMapper.update(comment);
    }

    /**
     * 删除评论
     *
     * @param id
     * @return
     */
    @Override
    public boolean delComment(Long id) {
        if(id==null||id<0){
            return false;
        }
        return commentMapper.deleteById(id);
    }

    /**
     * 通过商品id查找商品评论
     *
     * @param id 商品id
     * @return
     */
    @Override
    public List<Comment> getByGoodsId(Long id) {
        if(id<0)
            return null;
        return commentMapper.getByGoodsId(id);
    }

    /**
     * 创建评论
     *
     * @param commentAddDTO
     * @return
     */
    @Override
    public boolean addComment(CommentAddDTO commentAddDTO) {
        if(commentAddDTO==null)
            return false;
        User user=userMapper.getById(commentAddDTO.getUserId());
        Goods goods = goodsMapper.getById(commentAddDTO.getGoodsId());
        Comment comment = new Comment();
        comment.setGoodsId(goods.getId());
        comment.setGoodsName(goods.getGoodsName());
        comment.setUserId(user.getId());
        comment.setUsername(user.getUsername());
        comment.setCommentDescription(commentAddDTO.getCommentsDescription());
        comment.setCommentStatus(1);
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        return commentMapper.add(comment);
    }
}
